package com.example.LibrarySystem.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.LibrarySystem.mapper.UserMapper;
import com.example.LibrarySystem.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


//为jwt工具类，用来创建、解析jwt token
@Component
public class JwtUtil {

    @Autowired
    private static UserMapper userMapper;

    //token过期时间 一个月后token过期
    public static final Integer EXPIRE_DATE = 720;


    /**
     * 生成token
     *
     * @param userId
     * @param password
     * @return
     */
    public static String genToken(String userId, String password) {
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), EXPIRE_DATE))
                .sign(Algorithm.HMAC256(password)); // 以 password 作为 token 的密钥
    }

    /**
     * 获取token里的 userid
     *
     * @param token
     * @return
     */
    public static Integer verify(String token) {
        DecodedJWT decode = JWT.decode(token);
        String s = decode.getAudience().get(0);
        return Integer.parseInt(s);
    }


    //获取当前用户对象信息
    public static User getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){

                String userId = JWT.decode(token).getAudience().get(0);
                return userMapper.getUserById(Integer.parseInt(userId));
            }
        } catch (Exception e) {
            return null;
        }

        return null;
    }
}
